<template>
  <div class="flightList">
    <!--主体部分 -->
    <el-main>
      <!-- 航班列表 -->
      <div>
        <div style="display:flex;justyfy-content:flex-end;margin:10px 0">
          <el-button type="primary" icon="el-icon-refresh" @click="getData(a)"></el-button>
        </div>
        <el-table :data="pagedList" border style="width: 100%" highlight-current-row
          :cell-style="{textAlign: 'center'}">
          <el-table-column label="航班号">
            <template v-slot:default="slotProps">
              {{slotProps.row.flightName}}
            </template>
          </el-table-column>
          <el-table-column label="航班细节" min-width="250px">
            <template v-slot:default="slotProps">
              <div class="flight-detail">
                <div class="flight-detail">
                  <div class="detail-box">
                    <div class="detail-time" style="font-size:17px">
                      {{slotProps.row.startTime}}
                    </div>
                    <div class='detail-airport' style="font-size:17px">
                      {{slotProps.row.startPos}}
                    </div>
                  </div>
                  <div class="detail-arrow">
                    <div>
                      <img src="../assets/flight_information.png" width="75px" height="20px">
                    </div>
                    <div style="font-size:10px">
                      总时间
                      {{getHour(slotProps.row.startTime,slotProps.row.endTime)}}时{{getMin(slotProps.row.startTime,slotProps.row.endTime)}}分
                    </div>
                  </div>
                  <div class="detail-box">
                    <div class="detail-time" style="font-size:17px">
                      {{slotProps.row.endTime}}
                    </div>
                    <div class="detail-airport" style="font-size:17px">
                      {{slotProps.row.endPos}}
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="seatNo" label="座位号" class-name="seat-no"></el-table-column>
          <el-table-column prop="passengerId" label="乘客ID" min-width="150px"></el-table-column>
          <el-table-column label="航班状态">
            <template v-slot:default="slotProps">
              <el-tag effect="dark" :type="states.type[slotProps.row.state]">{{judgeState(slotProps.row)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <el-table-column label="操作" class="flight-option" min-width="150px">
            <template v-slot:default="slotProps" v-if="checkable">
              <template>
                <div>
                  <el-button @click="showDeleteAlert(slotProps.row)" :disabled="inRefunding" :loading="inRefunding">退 订
                  </el-button>
                  <el-button @click="select_seat(slotProps.row)"
                    v-if="slotProps.row.seatNo=='' &&  (slotProps.row.state==2||slotProps.row.state==-1)">选 座
                  </el-button>
                  <el-button @click="rebookTicket(slotProps.row)" v-if="slotProps.row.seatNo==''">改 签</el-button>
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <!-- //底部分页栏 -->
    <el-footer class="footer">
      <el-pagination background layout="total,prev,pager,next" v-bind:page-count="totalPage"
        v-bind:total="totalAirplanes" v-bind:page-size="pageSize" @current-change="setCurrentPage"></el-pagination>
    </el-footer>
    <!-- 选座信息弹窗 -->
    <div>
      <el-dialog :visible.sync="CheckSeat.checkSeatVisible" width="50%">
        <check-seat v-on:cancel-check="CheckSeat.checkSeatVisible=false" v-bind:ticketInfo="CheckSeat.detailInfo">
        </check-seat>
      </el-dialog>
    </div>
    <!-- 改签信息弹窗 -->
    <div>
      <el-dialog :title="'正在为'+this.rebookTicketDialog.detailInfo.passengerId+'改签'"
        :visible.sync="rebookTicketDialog.dialogVisible" width="100%">
        <airplane-list v-on:make-order="makeRebook" :isRebook="true"></airplane-list>
      </el-dialog>
    </div>
  </div>
</template>
<script >
import PlaneDetail from "./PlaneDetail";
import CheckSeat from "./CheckSeat.vue";
import AirplaneList from "./AirplaneList.vue";
import axios from "axios";
export default {
  components: { PlaneDetail, CheckSeat, AirplaneList },
  name: "UserFlightList",
  props: ["a"],
  data() {
    return {
      userInfo: this.$GLOBAL,
      headDate: Number,
      rawList: [],
      currentPage: 1,
      pageSize: 6,
      states: {
        code: {
          "4": "已起飞",
          "3": "登机",
          "2": "选座",
          "1": "等候",
          "-1": "延误",
          "-2": "取消"
        },
        type: {
          "4": "info",
          "3": "",
          "2": "",
          "1": "success",
          "-1": "warning",
          "-2": "danger"
        }
      },
      CheckSeat: {
        checkSeatVisible: false,
        detailInfo: {}
      },
      flightDetail: {
        dialogVisible: false,
        detailInfo: {}
      },
      rebookTicketDialog: {
        dialogVisible: false,
        detailInfo: {}
      },
      datePickerOptions: {
        disabledDate(time) {
          var today = new Date();
          today.setDate(today.getDate());
          return time.getTime() < today.getTime();
        }
      },
      //判断机票状态
      ticketSorts: {
        onWaiting: 0,
        onChecking: 0
      },
      //防止多次退票BUG
      inRefunding: false
    };
  },
  methods: {
    showDeleteAlert(ticketInfo) {
      this.$confirm("退票将在本月内降低您的信用等级，是否退票?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          if (res == "confirm") this.deleteOrder(ticketInfo);
        })
        .catch(res => {
          this.$message({
            type: "info",
            message: "已取消退票"
          });
        });
    },
    judgeState(ticket) {
      var state = ticket.state;
      var seatNo = ticket.seatNo;
      switch (state) {
        case -2:
          return "取消";
        case -1:
          return "延误";
        case 1:
          return "等候";
        case 2:
          if (seatNo === "") return "待选座";
          else return "已选座";
        case 3:
          return "登机";
        case 4:
          return "已起飞";
      }
    },
    getHour(start, end) {
      return Math.floor((new Date(end) - new Date(start)) / (60 * 60 * 1000));
    },
    getMin(start, end) {
      return Math.round(
        ((new Date(end) - new Date(start)) / (60 * 60 * 1000) -
          Math.floor((new Date(end) - new Date(start)) / (60 * 60 * 1000))) *
          60
      );
    },
    getData(filter) {
      // 根据当前过滤器查询数据
      if (filter == "all-ticket") {
        this.rawList = [];
        this.$axios
          .post(this.$GLOBAL.localHost + "list/", {
            userId: this.$GLOBAL.username
          })
          .then(response => {
            console.log("用户获取所有机票信息");
            console.log(response.data);
            for (let item of response.data.root) {
              this.rawList.push(item[0]);
            }
          })
          .catch(error => console.log(error));
      } else if (filter == "due-ticket") {
        // 先清空列表
        this.rawList = [];
        this.$axios
          .post(this.$GLOBAL.localHost + "list/", {
            userId: this.$GLOBAL.username
          })
          .then(response => {
            //初始化分类
            console.log(response);
            this.ticketSorts.onWaiting = 0;
            this.ticketSorts.onChecking = 0;
            //添加到未出行订单
            for (let item of response.data.root) {
              //航班起飞或者取消则视为已出行
              if (item[0].state != -2 && item[0].state != 4) {
                //如果没选座则加入待选座名单
                if (item[0].seatNo == "") this.ticketSorts.onChecking++;
                this.rawList.push(item[0]);
              }
            }
            //待出行机票的数量
            this.ticketSorts.onWaiting = this.rawList.length;
            this.$emit("sort-ticket", this.ticketSorts);
          })
          .catch(error => console.log(error));
      }
    },
    //退订
    deleteOrder(info) {
      console.log("in quit");
      this.inRefunding = true;
      this.$axios
        .post(this.$GLOBAL.localHost + "refund/", {
          ticketId: info.ticketId,
          userId: this.$GLOBAL.username
        })
        .then(res => {
          if (res.data.success == 1) {
            this.$message({
              message: "退票成功",
              type: "warning"
            });
          } else {
            this.$message({
              message: "退票失败",
              type: "error"
            });
          }
          //刷新数据
          this.getData(this.a);
          this.inRefunding = false;
        })
        .catch(error => {
          this.$message({
            message: "退票失败",
            type: "error"
          });
          console.log(error);
          this.inRefunding = false;
        });
    },
    //选座
    select_seat(info) {
      this.CheckSeat.detailInfo = info;
      this.CheckSeat.checkSeatVisible = true;
    },
    setCurrentPage(currentPage) {
      // 修改当前数据页码
      this.currentPage = currentPage;
    },
    showDetail(info) {
      // 显示航班详情
      this.flightDetail.detailInfo = info;
      this.flightDetail.dialogVisible = true;
    },
    hideDetail() {
      // 隐藏详情页
      this.flightDetail.detailInfo = null;
      this.flightDetail.dialogVisible = false;
    },
    rebookTicket(info) {
      this.rebookTicketDialog.detailInfo = info;
      this.rebookTicketDialog.dialogVisible = true;
    },
    makeRebook(info) {
      var data = {
        oldId: this.rebookTicketDialog.detailInfo.ticketId,
        oldflightId: this.rebookTicketDialog.detailInfo.flightId,
        newflightId: info.flights[0].flightId
      };
      axios
        .post(this.$GLOBAL.localHost + "endorse/", data)
        .then(res => {
          if (res.data.succcess == 1) {
            this.rebookTicketDialog.dialogVisible = false;
            this.$message({
              message: "改签成功",
              type: "success"
            });
          } else {
            this.$message({
              message: "改签失败",
              type: "error"
            });
          }
          //刷新数据
          this.getData(this.a);
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  computed: {
    checkable: function() {
      return this.a == "due-ticket" ? true : false;
    },
    //分页数据
    pagedList: function() {
      var start = (this.currentPage - 1) * this.pageSize;
      var end = start + this.pageSize;
      return this.rawList.slice(start, end);
    },
    // 总页数
    totalPage: function() {
      return this.rawList.length / this.pageSize;
    },
    // 总航班数
    totalAirplanes: function() {
      return this.rawList.length;
    }
  },
  watch: {
    // 每次标签名修改时获取数据
    a: function(newVal, oldVal) {
      this.getData(newVal);
    }
  },
  mounted() {
    this.getData(this.a);
  }
};
</script>
<style scoped>
* {
  font-size: 18px;
}
.header {
  font-weight: bolder;
  font-size: x-large;
  background-color: rgb(233, 238, 243);
}
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.flight-detail {
  display: flex;
  justify-content: center;
  align-content: space-around;
  text-align: center;
  color: black;
  padding: 5px;
}
.detail-box {
  padding: 0 5px;
}
.detail-airport {
  margin: 10px 0;
  min-height: 20px;
}
.detail-time {
  width: 100px;
  font-size: 30px;
}
.detail-arrow {
  font-size: 20px;
}
</style>
